<template>
  <div>
    <div class="n-layout-page-header">
      <n-card :bordered="false" title="我的申请">
        <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
          <template #statusSlot="{ model, field }">
            <n-input v-model:value="model[field]" />
          </template>
        </BasicForm>
      </n-card>
    </div>
    <n-card :bordered="false" class="mt-4 proCard">
      <BasicTable
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row) => row.id"
        ref="actionRef"
        :actionColumn="actionColumn"
        @update:checked-row-keys="onCheckedRow"
        id="moss-basicTable"
        :bordered="false"
      >
        <template #action>
          <TableAction />
        </template>
      </BasicTable>
    </n-card>

    <n-drawer v-model:show="showModal" :width="720" :mask-closable="false">
      <n-drawer-content :title="editTitle" :native-scrollbar="false">
        <GenerateForm ref="generateFormRef" :data="widgetForm" :disabled="true" />
        <n-timeline :icon-size="40">
          <n-timeline-item
            v-for="item in detailTasks"
            :key="item.id"
            :title="item.name"
            type="success"
            :time="item.applyTime"
          >
            <template #header>
              <span v-if="item.isApplicant">
                <n-tag>发起审批</n-tag>
              </span>
              <span v-if="!item.isApplicant">
                <n-space>
                  <n-tag>{{ item.name }}</n-tag>
                  <n-tag v-if="item.status === 1" :bordered="false" type="warning"
                    >未开始</n-tag
                  >
                  <n-tag v-if="item.status === 2" :bordered="false" type="info"
                    >进行中</n-tag
                  >
                  <n-tag v-if="item.status === 3" :bordered="false" type="success"
                    >通过</n-tag
                  >
                  <n-tag v-if="item.status === 4" :bordered="false" type="error"
                    >拒绝</n-tag
                  >
                </n-space>
              </span>
            </template>
            <template #icon>
              <n-icon v-for="a in item.approvalUsers" :key="a.id">
                <n-avatar round size="large" :src="a.avatar" />
              </n-icon>
            </template>
            <template v-if="item.ccUsers !== null && !item.isApplicant" #default>
              <div class="custom-flow-cc">
                <n-avatar size="large">抄送给</n-avatar>
              </div>
              <n-icon v-for="x in item.ccUsers" :key="x.id" style="margin-right: 45px">
                <n-avatar round size="large" :src="x.avatar" />
              </n-icon>
              <div v-if="item.applyOpinion" style="margin-top: 6px">
                <n-alert title="批复意见" type="info">
                  {{ item.applyOpinion }}
                </n-alert>
              </div>
            </template>
          </n-timeline-item>
        </n-timeline>
        <div>
          <n-form
            :model="fromValues"
            ref="formRef"
            label-placement="top"
            :label-width="120"
            class="py-4"
            style="width: 100%"
          >
            <n-form-item label="批复意见" path="applyOpinion">
              <n-input
                maxlength="300"
                show-count
                type="textarea"
                :autosize="{
                  minRows: 3,
                  maxRows: 5,
                }"
                v-model:value="fromValues.applyOpinion"
                filterable
                placeholder="请输入批复意见"
              />
            </n-form-item>
          </n-form>
        </div>
        <template #footer>
          <n-space>
            <n-button ghost icon-placement="left" @click="handleCloseModel">
              取消
            </n-button>
            <n-button type="error" :loading="formBtnLoading" @click="handleSubmitFlow(4)"
              >拒绝</n-button
            >
            <n-button type="primary" :loading="btnLoading" @click="handleSubmitFlow(3)"
              >同意</n-button
            >
          </n-space>
        </template>
      </n-drawer-content>
    </n-drawer>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, h, unref, onMounted } from "vue";
import { useMessage } from "naive-ui";
import { BasicForm, FormSchema, useForm } from "@/components/Form/index";
import { BasicTable, TableAction } from "@/components/Table";
import { detail as busDetail, approval } from "@/api/flow/flowBusiness";
import { page } from "@/api/flow/flowTask";
import { columns } from "./columns";
import { EditOutlined } from "@vicons/antd";
import { ResultEnum } from "@/enums/httpEnum";
import GenerateForm from "../../../components/naiveui/components/generate/GenerateForm.vue";
import console from "console";
const message = useMessage();
const actionRef = ref();
const showModal = ref(false);
const formBtnLoading = ref(false);
const btnLoading = ref(false);
const editTitle = ref("");
const generateFormRef = ref<any>(null);
const widgetForm = ref<any>(null);
const detailTasks = ref<any[]>([]);
// 1:未开始，2:进行中，3:通过，4:拒绝
const statusOptions = ref([
  { label: "未开始", value: 1 },
  { label: "进行中", value: 2 },
  { label: "通过", value: 3 },
  { label: "拒绝", value: 4 },
]);
const defaultValueRef = () => ({
  /** 任务ID*/
  id: null,
  /** 审批状态*/
  status: 3,
  /** 批复意见*/
  applyOpinion: "",
});
let fromValues = reactive(defaultValueRef());
/**
 * 表格查询参数定义
 */
const schemas: FormSchema[] = [
  /**查询参数*/
  {
    field: "title",
    component: "NInput",
    label: "流程任务名称",
    componentProps: {
      placeholder: "请输入流程任务名称",
    },
  },
  {
    field: "status",
    component: "NSelect",
    label: "审批状态",
    componentProps: {
      placeholder: "请选择审批状态",
      options: statusOptions,
    },
  },
];
/**
 * 表格查询注册
 */
const [register, { getFieldsValue }] = useForm({
  gridProps: { cols: "1 s:1 m:2 l:3 xl:4 2xl:4" },
  labelWidth: 120,
  schemas,
});
const actionColumn = reactive({
  width: 250,
  title: "操作",
  key: "action",
  fixed: "right",
  render(record) {
    return h(TableAction as any, {
      style: "text",
      actions: createActions(record),
    });
  },
});

function createActions(record) {
  return [
    {
      label: "审批",
      type: "primary",
      icon: EditOutlined,
      onClick: handleEdit.bind(null, record),
      ifShow: () => {
        return true;
      },
      //auth: ['basic_list'],
    },
  ];
}
const loadDataTable = async (res: any) => {
  return await page({ ...getFieldsValue(), ...res });
};

function onCheckedRow(rowKeys: any[]) {
  console.log(rowKeys);
}

function reloadTable() {
  actionRef.value.reload();
}

const handleBusDetail = async (id: number) => {
  const data = await busDetail({ id: id });
  if (data.code !== ResultEnum.SUCCESS) {
    const resultMsg = data.data ? data.data : "";
    message.error(data.msg + "-" + resultMsg);
  }
  if (data.code === ResultEnum.SUCCESS) {
    widgetForm.value = JSON.parse(data.data.originalFormData);
    detailTasks.value = data.data.nodeTasks;
  }
};
/**
 * 查询
 */
function handleSubmit() {
  reloadTable();
}
/**
 * 重置查询
 */
function handleReset() {
  reloadTable();
}
function resetFrom() {
  fromValues = Object.assign(unref(fromValues), defaultValueRef());
}
/**
 * 新增详情model
 * @param record
 * @param addStatus
 */
const handleEdit = (record: Recordable) => {
  showModal.value = true;
  editTitle.value = record.title + "详情";
  fromValues.id = record.id;
  handleBusDetail(record.busId);
};
/**
 * 快捷申请数据提交
 */
const handleSubmitFlow = async (status: number) => {
  status === 3 ? (btnLoading.value = true) : (formBtnLoading.value = true);
  fromValues.status = status;
  const data = await approval(fromValues);
  if (data.code !== ResultEnum.SUCCESS) {
    const resultMsg = data.data ? data.data : "";
    message.error(data.msg + "-" + resultMsg);
    btnLoading.value = false;
    formBtnLoading.value = false;
  }
  if (data.code === ResultEnum.SUCCESS) {
    message.success(data.msg);
    btnLoading.value = false;
    formBtnLoading.value = false;
    handleCloseModel();
    reloadTable();
  }
};
/**
 * 新增编辑关闭model
 */
function handleCloseModel() {
  resetFrom();
  showModal.value = false;
}
onMounted(() => {});
</script>

<style lang="less" scoped>
.custom-flow-cc {
  width: 60px;
  height: 40px;
  display: flex;
  align-items: center;
  float: left;
}
</style>
